package com.daJiao.handler.security;

import cn.hutool.json.JSONUtil;
import com.daJiao.constants.RedisKeyPrefix;
import com.daJiao.domain.SecurityUserDetails;
import com.daJiao.domain.WrapMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>Title:      CustomerAuthenticationSuccessHandler. </p>
 * <p>Description 认证成功处理器 </p>
 * <p>Copyright: Copyright (c) 2016</p>
 * <p>Company:    医百科技有限公司 </p>
 *
 * @author <a href="yangwensheng@100doc.com.cn"/>杨文生</a>
 * @Date 2021/12/07 14:45
 */
@Component("customerAuthenticationSuccessHandler")
public class CustomerAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        // 用uuid来做token
        String token = UUID.randomUUID().toString();
        // 将用户信息存入redis中
        SecurityUserDetails securityUser = (SecurityUserDetails) authentication.getPrincipal();
        ValueOperations operations = redisTemplate.opsForValue();
        operations.set(RedisKeyPrefix.ONLINEUSER + token, JSONUtil.toJsonStr(securityUser));
        redisTemplate.expire(RedisKeyPrefix.ONLINEUSER + token, RedisKeyPrefix.USER_EXPIRE_TIME_MINUTE, TimeUnit.SECONDS);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(objectMapper.writeValueAsString(WrapMapper.ok(token)));
    }
}
